﻿using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;
using Z.EntityFramework.Plus;

namespace OpenPasteSpider.usermodel
{

    /// <summary>
    /// 权限列表
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
    public class RoleInfoAppService : OpenPasteSpiderAppService
    {

        //private readonly IRepository<RoleInfo, int> _repository;


        private readonly IOpenPasteSpiderDbContext _dbContext;


        public RoleInfoAppService(IOpenPasteSpiderDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <param name="groupid"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagedResultDto<RoleInfoListDto>> GetListAsync(int page = 1, int size = 20, int groupid = 0)
        {

            var query = _dbContext.RoleInfo.Where(t => 1 == 1).AsNoTracking().OrderBy(xy => xy.Id);

            var pagedResultDto = new PagedResultDto<RoleInfoListDto>();
            pagedResultDto.TotalCount = await query.CountAsync();
            var userList = await query.Page(page, size).ToListAsync();
            var temList = ObjectMapper.Map<List<RoleInfo>, List<RoleInfoListDto>>(userList);


            if (groupid > 0)
            {
                foreach (var item in temList)
                {
                    item.IsEnable = false;
                }

                var binds = await _dbContext.GradeRole.Where(x => x.GradeId == groupid).AsNoTracking().ToListAsync();
                if (binds != null && binds.Count > 0)
                {
                    var roleids = binds.Select(x => x.RoleId).ToList();
                    var hitroles = temList.Where(x => roleids.Contains(x.Id)).ToList();
                    foreach (var item in hitroles)
                    {
                        item.IsEnable = true;
                    }
                }

            }
            pagedResultDto.Items = temList;

            return pagedResultDto;
        }

        /// <summary>
        /// 更新绑定
        /// </summary>
        /// <param name="groupid"></param>
        /// <param name="roleid"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<int> UpdateBindRole(int groupid, int roleid, bool state)
        {
            if (state)
            {
                var find = await _dbContext.GradeRole.Where(x => x.GradeId == groupid && x.RoleId == roleid).AsNoTracking().FirstOrDefaultAsync();
                if (find == null || find == default)
                {
                    var one = new GradeRole();
                    one.GradeId = groupid;
                    one.RoleId = roleid;
                    _dbContext.Add(one);
                    await _dbContext.SaveChangesAsync();
                }
            }
            else
            {
                var find = await _dbContext.GradeRole.Where(x => x.GradeId == groupid && x.RoleId == roleid).FirstOrDefaultAsync();
                if (find != null && find != default)
                {
                    _dbContext.Remove(find);
                    await _dbContext.SaveChangesAsync();
                }
            }

            return 1;
        }

        /// <summary>
        /// 根据ID获取单项权限列表
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public RoleInfoDto GetByIdAsync(int id)
        {
            var query = _dbContext.RoleInfo.Where(t => t.Id == id).FirstOrDefault();
            var temList = ObjectMapper.Map<RoleInfo, RoleInfoDto>(query);
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息权限列表
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public RoleInfoUpdateDto GetInfoForUpdateAsync(int id)
        {
            var query = _dbContext.RoleInfo.Where(t => t.Id == id).FirstOrDefault();
            var temList = ObjectMapper.Map<RoleInfo, RoleInfoUpdateDto>(query);
            return temList;
        }


        /// <summary>
        /// 添加一个权限列表
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork(false)]
        [HttpPost]
        public async Task<RoleInfoDto> CreateItemAsync(RoleInfoAddDto input)
        {
            var finddata = _dbContext.RoleInfo.Where(x => x.Role == input.Name && x.Model == input.Model).AsNoTracking().FirstOrDefault();
            if (finddata != null && finddata != default)
            {
                throw new PasteException("数据重复了，无法重复写入！");
            }

            var newu = ObjectMapper.Map<RoleInfoAddDto, RoleInfo>(input);
            if (input.FatherId != 0)
            {
                var find = _dbContext.RoleInfo.Where(x => x.Id == input.FatherId).AsNoTracking().FirstOrDefault();
                if (find == null || find == default)
                {
                    throw new PasteException("不存在的父级信息，请重试");
                }
                newu.FatherStr = $"{find.FatherStr},";
            }
            newu.IsEnable = true;//添加自定义
            //var updated = await _repository.InsertAsync(newu, true);
            _dbContext.Add(newu);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<RoleInfo, RoleInfoDto>(newu);

            if (newu.FatherId != 0)
            {
                //await _dbContext.RoleInfo.Where(x => x.Id == newu.Id).UpdateAsync(x => new RoleInfo { FatherStr = $"{x.FatherStr},{newu.Id}," });
                newu.FatherStr = $"{newu.FatherStr},{newu.Id},";
            }
            else
            {
                //await _dbContext.RoleInfo.Where(x => x.Id == newu.Id).UpdateAsync(x => new RoleInfo { FatherStr = $"{newu.Id}," });
                newu.FatherStr = $"{newu.Id},";
            }
            await _dbContext.SaveChangesAsync();

            return backinfo;
        }
        /// <summary>
        /// 更新一个权限列表
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [UnitOfWork(false)]
        [HttpPost]
        public async Task<RoleInfoDto> UpdateItemAsync(RoleInfoUpdateDto input)
        {

            var info = await _dbContext.RoleInfo.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new UserFriendlyException("需要查询的信息不存在", "404");
            }

            var finddata = _dbContext.RoleInfo.Where(x => x.Role == input.Name && x.Model == input.Model && x.Id != input.Id).AsNoTracking().FirstOrDefault();
            if (finddata != null && finddata != default)
            {
                throw new PasteException("数据重复了，无法重复写入！");
            }

            if (info.FatherId != input.FatherId)
            {
                var find = _dbContext.RoleInfo.Where(x => x.Id == input.FatherId).AsNoTracking().FirstOrDefault();
                if (find == null || find == default)
                {
                    throw new PasteException("不存在的父级信息，请重试");
                }
                info.FatherStr = $"{info.FatherStr},{info.Id},";
            }

            ObjectMapper.Map<RoleInfoUpdateDto, RoleInfo>(input, info);
            var backinfo = ObjectMapper.Map<RoleInfo, RoleInfoDto>(info);
            await _dbContext.SaveChangesAsync();

            return backinfo;
        }

    }
}
